<template>
    <div class="cardContent">
        <a-page-header :title="department.name" sub-title="欢迎部长查看部门信息">
            <template #extra>
                <a-button type="primary" ghost @click="openDeptModal">编辑部门信息</a-button>
                <a-button type="primary" @click="openRoleModal({})">新增部门角色</a-button>
            </template>
            <a-descriptions size="small" :column="3">
                <a-descriptions-item label="部门编号">{{department.code}}</a-descriptions-item>
                <a-descriptions-item label="部长">{{loginUser.username}}</a-descriptions-item>
                <a-descriptions-item label="部门电话">{{department.tel}}</a-descriptions-item>
                <a-descriptions-item label="部门邮箱">{{department.email}}</a-descriptions-item>
                <a-descriptions-item label="部门描述">
                    {{department.remark}}
                </a-descriptions-item>
            </a-descriptions>
            <template #footer>
                <a-tabs>
                    <a-tab-pane key="1">
                        <template #tab>
                            <span>
                              <apple-outlined/>
                              角色列表
                            </span>
                        </template>
                        <a-table :dataSource="roleList"
                                 style="margin-top: 10px"
                                 :columns="roleColumns"
                                 :pagination="rolePagination"
                                 @change="rolePaginationChange"
                                 size="small"
                                 bordered>
                            <template #bodyCell="{text,record,index,column}">
                                <template v-if="column.key == 'isLeader'">
                                    {{text == 1 ? '部长' : '普通职员'}}
                                </template>
                                <a-space v-if="column.key == 'action'">
                                    <a-button type="primary" ghost
                                              v-if="record.isLeader == 0"
                                              @click="openRoleUserDraw(record.id)">
                                        用户
                                    </a-button>
                                    <a-button type="primary" @click="openRoleModal(record)">
                                        编辑
                                    </a-button>
                                    <a-popconfirm
                                            title="是否确认删除?"
                                            ok-text="是"
                                            cancel-text="否"
                                            @confirm="okRoleDelete(record.id)"
                                    >
                                        <a-button type="danger" v-if="record.isLeader != 1">删除</a-button>
                                    </a-popconfirm>
                                </a-space>
                            </template>
                        </a-table>
                    </a-tab-pane>
                    <a-tab-pane key="2">
                        <template #tab>
                            <span>
                              <android-outlined/>
                              用户列表
                            </span>
                        </template>
                        <a-table :dataSource="userList"
                                 style="margin-top: 10px"
                                 :columns="userColumns"
                                 :pagination="userPagination"
                                 @change="userPaginationChange"
                                 size="small"
                                 bordered>
                            <template #bodyCell="{text,record,index,column}">
                                <template v-if="column.key == 'status'">
                                    {{text == 0 ? "在职" : (text == 1 ? "辞职" : (text == 2 ? "辞退" : "停职"))}}
                                </template>
                                <template v-if="column.key == 'pic'">
                                    <a-image
                                            :src="text != undefined ? text : 'https://lyj-mall-bucket.oss-cn-guangzhou.aliyuncs.com/20230129/default.png'"
                                            style="width: 32px;height: 32px"></a-image>
                                </template>
                                <template v-if="column.key == 'birthday'">
                                    {{formatDate(text,'YYYY-MM-DD')}}
                                </template>
                                <a-space v-if="column.key == 'action'">
                                    <a-button type="primary" ghost @click="getUserInfo(record.id)">详情</a-button>
                                    <a-popconfirm
                                            v-if="record.id != department.leader"
                                            title="是否确认删除?"
                                            ok-text="是"
                                            cancel-text="否"
                                            @confirm="okCancel(record.id)"
                                    >
                                        <a-button type="danger" ghost>解除关联</a-button>
                                    </a-popconfirm>
                                </a-space>
                            </template>
                        </a-table>
                    </a-tab-pane>
                </a-tabs>
            </template>
        </a-page-header>
        <a-modal v-model:visible="deptModalVisible" title="编辑部门信息" @ok="submitDept">
            <a-form
                    :model="tempDepartment"
                    :label-col="{ span: 4 }"
                    :wrapper-col="{ span: 20 }"
                    autocomplete="off">
                <a-form-item label="部门ID">
                    <a-input v-model:value="tempDepartment.id" disabled/>
                </a-form-item>
                <a-form-item label="部门名称" v-bind="deptRef.validateInfos.name">
                    <a-input v-model:value="tempDepartment.name"/>
                </a-form-item>
                <a-form-item label="部门编号">
                    <a-input v-model:value="tempDepartment.code" disabled/>
                </a-form-item>
                <a-form-item label="部门电话" v-bind="deptRef.validateInfos.tel">
                    <a-input v-model:value="tempDepartment.tel"/>
                </a-form-item>
                <a-form-item label="部门邮箱" v-bind="deptRef.validateInfos.email">
                    <a-input v-model:value="tempDepartment.email"/>
                </a-form-item>
                <a-form-item label="部门描述">
                    <a-textarea
                            v-model:value="tempDepartment.remark"
                            :rows="4"/>
                </a-form-item>
            </a-form>
        </a-modal>
        <a-modal v-model:visible="roleModalVisible" title="编辑角色信息" @ok="submitRole">
            <a-form
                    :model="role"
                    :label-col="{ span: 4 }"
                    :wrapper-col="{ span: 20 }"
                    autocomplete="off">
                <a-form-item label="角色名称" v-bind="roleRef.validateInfos.name">
                    <a-input v-model:value="role.name"/>
                </a-form-item>
                <a-form-item label="基本工资" v-bind="roleRef.validateInfos.baseSalary">
                    <a-input-number v-model:value="role.baseSalary" addon-after="￥" min="1500"/>
                </a-form-item>
                <a-form-item label="角色描述">
                    <a-textarea
                            v-model:value="role.remark"
                            :rows="4"/>
                </a-form-item>
            </a-form>
        </a-modal>
        <!--        查看角色关联用户列表-->
        <a-drawer
                v-model:visible="roleUserVisible"
                class="custom-class"
                width="600"
                title="角色用户"
                placement="right"
        >
            <a-input-search
                    v-model:value="searchRoleUserCondition.keyword"
                    style="margin-top: 10px"
                    placeholder="请输入关键词搜索..."
                    enter-button
                    @search="onSearchRoleUser"
            />
            <a-button type="primary" style="margin-top: 10px" @click="openAssociateUserModal">关联用户
            </a-button>
            <a-table :dataSource="roleUserList"
                     style="margin-top: 10px"
                     :columns="roleUserColumns"
                     :pagination="false"
                     size="small"
                     bordered>
                <template #bodyCell="{text,record,index,column}">
                    <template v-if="column.key == 'status'">
                        {{text == 0 ? "在职" : (text == 1 ? "辞职" : (text == 2 ? "辞退" : "停职"))}}
                    </template>
                    <a-space v-if="column.key == 'action'">
                        <a-popconfirm
                                title="是否确认取消关联?"
                                ok-text="是"
                                cancel-text="否"
                                @confirm="okCancel(record.id)"
                        >
                            <a-button type="danger">解除关联</a-button>
                        </a-popconfirm>
                    </a-space>
                </template>
            </a-table>
        </a-drawer>
        <!--        未关联角色的用户-->
        <a-modal v-model:visible="associateModalVisible" title="用户列表" @ok="okAssociateUser">
            <a-input-search
                    v-model:value="notAssociateUserCondition.keyword"
                    style="margin-top: 10px"
                    placeholder="请输入关键词搜索..."
                    enter-button
                    @search="onSearchNotAssociateUser"
            />
            <a-table :dataSource="notAssociateUserList"
                     style="margin-top: 10px"
                     :columns="notAssociateUserColumns"
                     :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
                     row-key="id"
                     :pagination="false"
                     size="small"
                     bordered>
                <template #bodyCell="{text,record,index,column}">
                    <template v-if="column.key == 'status'">
                        {{text == 0 ? "在职" : (text == 1 ? "辞职" : (text == 2 ? "辞退" : "停职"))}}
                    </template>
                </template>
            </a-table>
        </a-modal>
        <!--        用户详情-->
        <a-drawer
                v-model:visible="userInfoVisible"
                class="custom-class"
                width="800"
                title="用户信息详情"
                placement="right"
                :footer-style="{textAlign: 'right'}"
        >
            <a-descriptions layout="vertical" bordered>
                <template #title>
                    <a-image :src="userInfo.pic" style="border-radius: 50%;height: 32px;width: 32px"></a-image>
                    {{userInfo.username}}
                </template>
                <a-descriptions-item label="账号">{{userInfo.userCode}}</a-descriptions-item>
                <a-descriptions-item label="工号">{{userInfo.workNum}}</a-descriptions-item>
                <a-descriptions-item label="出生日期">{{formatDate(userInfo.birthday,'YYYY-MM-DD')}}</a-descriptions-item>
                <a-descriptions-item label="电话">{{userInfo.phone}}</a-descriptions-item>
                <a-descriptions-item label="邮箱" :span="2">{{userInfo.email}}</a-descriptions-item>
                <a-descriptions-item label="状态" :span="3">
                    <a-badge v-if="userInfo.status == 0" status="processing" text="在职"/>
                    <a-badge v-if="userInfo.status == 1" status="warning" text="离职"/>
                    <a-badge v-if="userInfo.status == 2" status="error" text="辞退"/>
                </a-descriptions-item>
                <a-descriptions-item label="所属部门">{{userInfo.departmentName}}</a-descriptions-item>
                <a-descriptions-item label="角色">{{userInfo.roleName}}</a-descriptions-item>
                <a-descriptions-item label="基本薪资">{{userInfo.baseAmount}}</a-descriptions-item>
                <a-descriptions-item label="操作记录">
                    入职办理人：{{userInfo.createName}}
                    <br/>
                    入职办理时间: {{formatDate(userInfo.createDate,'YYYY-MM-DD HH:mm:ss')}}
                    <br/>
                    <br/>
                    最近信息修改人: {{userInfo.updateName}}
                    <br/>
                    最近信息修改时间: {{formatDate(userInfo.updateDate,'YYYY-MM-DD HH:mm:ss')}}
                </a-descriptions-item>
            </a-descriptions>
            <template #extra>
                <a-button type="primary" @click="userInfoVisible = false">关闭</a-button>
            </template>
        </a-drawer>
    </div>
</template>

<script>
    import {ExclamationCircleOutlined, SyncOutlined} from "@ant-design/icons-vue";
    import {Form, message} from "ant-design-vue";
    import {onMounted, ref} from "vue";
    import axios from "axios";
    import {isEmpty} from "@/utils/Tool";
    import dayjs from "dayjs";
    import store from "@/store";

    export default {
        name: "MyDepartment",
        components: {
            SyncOutlined,
            ExclamationCircleOutlined,
        },
        setup() {
            const loginUser = ref({})
            const department = ref({})
            const tempDepartment = ref({
                name: '',
                tel: '',
                email: ''
            })
            const userColumns = [
                {
                    title: '账号',
                    dataIndex: 'userCode',
                    key: 'userCode',
                },
                {
                    title: '头像',
                    dataIndex: 'pic',
                    key: 'pic',
                },
                {
                    title: '用户名',
                    dataIndex: 'username',
                    key: 'username',
                },
                {
                    title: '工号',
                    dataIndex: 'workNum',
                    key: 'workNum',
                },
                {
                    title: '角色',
                    dataIndex: 'roleName',
                    key: 'roleName',
                },
                {
                    title: '电话号码',
                    dataIndex: 'phone',
                    key: 'phone',
                },
                {
                    title: '生日',
                    dataIndex: 'birthday',
                    key: 'birthday',
                },
                {
                    title: '状态',
                    dataIndex: 'status',
                    key: 'status',
                },
                {
                    title: '操作',
                    key: 'action',
                    width: '200px'
                }
            ]
            const userInfo = ref({})
            const userList = ref()
            const userPagination = ref({
                current: 1,
                pageSize: 5,
            })

            const role = ref({
                name: '',
                baseSalary: undefined
            })
            const roleColumns = [
                {
                    title: '角色名称',
                    dataIndex: 'name',
                    key: 'name',
                },
                {
                    title: '基本工资',
                    dataIndex: 'baseSalary',
                    key: 'baseSalary',
                },
                {
                    title: '上级',
                    dataIndex: 'isLeader',
                    key: 'isLeader',
                },
                {
                    title: ' 描述',
                    dataIndex: 'remark',
                    key: 'remark',
                },
                {
                    title: '操作',
                    key: 'action',
                }
            ]
            const roleList = ref()
            const rolePagination = ref({
                current: 1,
                pageSize: 5,
            })
            const searchRoleUserCondition = ref({})
            const roleUserColumns = [
                {
                    title: '用户账号',
                    dataIndex: 'userCode',
                    key: 'userCode',
                    align: 'center',
                },
                {
                    title: '用户名',
                    dataIndex: 'username',
                    key: 'username',
                    align: 'center',
                },
                {
                    title: '状态',
                    dataIndex: 'status',
                    key: 'status',
                    align: 'center',
                },
                {
                    title: '操作',
                    key: 'action',
                    align: 'center',
                    width: '200px'
                }
            ]
            const roleUserList = ref([])
            const notAssociateUserCondition = ref({})
            const notAssociateUserList = ref([])
            const notAssociateUserColumns = [
                {
                    title: '用户账号',
                    dataIndex: 'userCode',
                    key: 'userCode',
                    align: 'center',
                },
                {
                    title: '用户名',
                    dataIndex: 'username',
                    key: 'username',
                    align: 'center',
                },
                {
                    title: '状态',
                    dataIndex: 'status',
                    key: 'status',
                    align: 'center',
                },
            ]
            const selectedRowKeys = ref([])

            const deptModalVisible = ref(false)
            const roleModalVisible = ref(false)
            const roleUserVisible = ref(false);
            const associateModalVisible = ref(false);
            const userInfoVisible = ref(false);

            const useForm = Form.useForm
            const deptRef = useForm(tempDepartment, {
                name: [{required: true, message: '请输入部门名称', trigger: ['submit', 'change']}],
                tel: [{required: true, message: '电话号码不能为空', trigger: ['submit', 'change']},
                    {
                        pattern: /^(0\d{2,3})-?(\d{7,8})$/,
                        message: '电话号码非法',
                        trigger: ['submit', 'change']
                    }],
                email: [{required: true, message: '邮箱不能为空', trigger: ['submit', 'change']},
                    {pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: '邮箱非法', trigger: ['change']}],
            })
            const roleRef = useForm(role, {
                name: [{required: true, message: '请输入角色名称', trigger: ['change']}],
                baseSalary: [{required: true, message: '基本工资不能为空', trigger: ['change']}],
            })

            const onSearchRoleUser = () => {
                axios.get('user/queryByRoleIdAndKeyword', {
                    params: {
                        roleId: searchRoleUserCondition.value.roleId,
                        keyword: searchRoleUserCondition.value.keyword
                    }
                }).then(rs => {
                    roleUserList.value = rs.data
                })
            }

            const openAssociateUserModal = () => {
                notAssociateUserCondition.value.roleId = searchRoleUserCondition.value.roleId
                notAssociateUserCondition.value.keyword = null
                onSearchNotAssociateUser()
                associateModalVisible.value = true
            }

            const okCancel = (userId) => {
                axios.get('user/cancelAssociate/' + userId).then(rs => {
                    if (rs.code == 200) {
                        message.success("取消关联成功")
                        onSearchRoleUser()
                        userLoad()
                    } else {
                        message.error(rs.message)
                    }
                })
            }

            const okAssociateUser = () => {
                axios.post('user/associate', {
                    roleId: notAssociateUserCondition.value.roleId,
                    userIds: selectedRowKeys.value
                }).then(rs => {
                    if (rs.code == 200) {
                        message.success("关联用户成功")
                        associateModalVisible.value = false
                        onSearchRoleUser()
                        userLoad()
                    } else {
                        message.error(rs.message)
                    }
                })
            }

            const onSearchNotAssociateUser = () => {
                selectedRowKeys.value = []
                axios.get('user/queryByKeywordExcludeRole/', {
                    params: {
                        keyword: notAssociateUserCondition.value.keyword
                    }
                }).then(rs => {
                    notAssociateUserList.value = rs.data
                })
            }

            const onSelectChange = (keys) => {
                console.log("选择的ids", keys)
                selectedRowKeys.value = keys
            }

            const openRoleUserDraw = (id) => {
                console.log("角色Id", id)
                searchRoleUserCondition.value.roleId = id
                onSearchRoleUser()
                roleUserVisible.value = true
            }

            const getUserInfo = (userId) => {
                console.log("要获取用户详情的id：", userId)
                axios.get('user/getUserInfo/' + userId).then(rs => {
                    userInfo.value = rs.data
                    userInfoVisible.value = true
                })
            }

            const load = () => {
                axios.get('department/getDepartmentById/' + loginUser.value.deptId).then(rs => {
                    department.value = rs.data
                })
            }

            const openDeptModal = () => {
                tempDepartment.value = JSON.parse(JSON.stringify(department.value))
                deptModalVisible.value = true
            }

            const openRoleModal = (obj) => {
                role.value = JSON.parse(JSON.stringify(obj))
                if (isEmpty(role.value)) {
                    console.log("新增")
                    roleRef.resetFields()
                    role.value.isDepartmentRole = 1
                    role.value.departmentId = loginUser.value.deptId
                    role.value.isLeader = 0
                }
                roleModalVisible.value = true
            }

            const submitDept = () => {
                deptRef.validate().then(() => {
                    console.log("校验成功")
                    axios.put('department/update', tempDepartment.value).then(rs => {
                        if (rs.code == 200) {
                            message.success("成功更新部门信息")
                            load()
                            deptModalVisible.value = false
                        } else {
                            message.error(rs.message)
                        }
                    })
                }).catch(() => {
                    console.log("校验失败")
                })

            }

            const submitRole = () => {
                roleRef.validate().then(() => {
                    console.log("通过校验")
                    axios.post('role/saveOrUpdate', role.value).then(rs => {
                        if (rs.code == 200) {
                            if (isEmpty(role.value.id)) {
                                message.success("成功新增角色")
                            } else {
                                message.success("成功更新角色信息")
                            }
                            roleLoad()
                            roleModalVisible.value = false
                        } else {
                            message.error(rs.message)
                        }
                    })
                }).catch(() => {
                    console.log("校验失败")
                })

            }

            const okRoleDelete = (id) => {
                console.log("要删除的ID：" + id)
                axios.delete('/role/deleteById/' + id).then(rs => {
                    if (rs.code == 200) {
                        message.success("角色删除成功")
                        roleLoad()
                        userLoad()
                    } else {
                        message.error(rs.message)
                    }
                })
            }

            const userLoad = () => {
                axios.get('/user/queryByDeptId', {
                    params: {
                        pageNum: rolePagination.value.current,
                        pageSize: rolePagination.value.pageSize,
                        departmentId: loginUser.value.deptId
                    }
                }).then(rs => {
                    console.log("查找结果：", rs)
                    userList.value = rs.data.records
                    userPagination.value.total = rs.data.total
                })
            }

            const roleLoad = () => {
                axios.get('/role/queryPageByCondition', {
                    params: {
                        pageNum: rolePagination.value.current,
                        pageSize: rolePagination.value.pageSize,
                        departmentId: loginUser.value.deptId
                    }
                }).then(rs => {
                    console.log("查找结果：", rs)
                    roleList.value = rs.data.records
                    rolePagination.value.total = rs.data.total
                })
            }

            const userPaginationChange = (pageInfo) => {
                userPagination.value = pageInfo
                userLoad()
            }
            const rolePaginationChange = (pageInfo) => {
                rolePagination.value = pageInfo
                roleLoad()
            }

            const formatDate = (time, format) => {
                return dayjs(time).format(format)
            }

            onMounted(() => {
                loginUser.value = store.state.user
                load()
                userLoad()
                roleLoad()
            })
            return {
                loginUser,
                department,
                tempDepartment,
                load,
                userColumns,
                userList,
                userInfo,
                userPagination,
                userPaginationChange,
                roleList,
                roleColumns,
                rolePagination,
                rolePaginationChange,
                formatDate,
                deptModalVisible,
                openDeptModal,
                submitDept,
                role,
                roleModalVisible,
                submitRole,
                openRoleModal,
                okRoleDelete,
                roleUserVisible,
                searchRoleUserCondition,
                onSearchRoleUser,
                openAssociateUserModal,
                roleUserList,
                roleUserColumns,
                okCancel,
                associateModalVisible,
                okAssociateUser,
                notAssociateUserCondition,
                onSearchNotAssociateUser,
                notAssociateUserList,
                notAssociateUserColumns,
                selectedRowKeys,
                onSelectChange,
                openRoleUserDraw,
                getUserInfo,
                userInfoVisible,
                deptRef,
                roleRef
            }
        }
    }
</script>

<style scoped>
    .cardContent {
        background: #fff;
        margin: 10px 10px 0 10px;
        padding: 15px;
    }
</style>